package com.bayss.core.util;

import com.bayss.core.entity.weixin.AccessToken;
import com.bayss.core.entity.weixin.LotteryTemplates;
import com.bayss.core.entity.weixin.TemplateData;
import com.bayss.core.entity.weixin.WxTemplates;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class WeixinUtil {
    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject HttpRequest(String request, String RequestMethod, String output) {
        @SuppressWarnings("unused")
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            //建立连接
            URL url = new URL(request);
            System.out.println("建立连接");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(RequestMethod);
            if (output != null) {
                OutputStream out = connection.getOutputStream();
                out.write(output.getBytes("UTF-8"));
                out.close();
            }
            //流处理
            InputStream input = connection.getInputStream();
            InputStreamReader inputReader = new InputStreamReader(input, "UTF-8");
            BufferedReader reader = new BufferedReader(inputReader);
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            //关闭连接、释放资源
            reader.close();
            inputReader.close();
            input.close();
            input = null;
            connection.disconnect();
            System.out.println(buffer.toString());
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
        }
        return jsonObject;
    }

    //发送小程序模板消息
    public static boolean sendTemplate(String formId, String opendid, String nickName, String giftname) {
        WeixinApi a = new WeixinApi();
        String token = a.getWeAppAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token;
        WxTemplates template = new WxTemplates();
        template.setTouser(opendid);
        template.setTemplate_id("vXnbJNYp-3qAIP2ynusoG1hL0Q-QUfYA22hxHdAI0DA");
        template.setForm_id(formId);
        template.setPage("pages/mePage/index");
        Map<String, TemplateData> data = new HashMap<String, TemplateData>();

        TemplateData temp = new TemplateData();
        temp.setValue(giftname);
        data.put("keyword1", temp);

        TemplateData temp1 = new TemplateData();
        temp1.setValue("1份");
        data.put("keyword2", temp1);

        TemplateData temp2 = new TemplateData();
        temp2.setValue(nickName);
        data.put("keyword3", temp2);

        TemplateData temp3 = new TemplateData();
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        temp3.setValue(formatter.format(new Date()));
        data.put("keyword4", temp3);

        template.setData(data);
        String jsonString = JSONObject.fromObject(template).toString();
        System.out.println(jsonString);
        JSONObject jsonObject = WeixinUtil.HttpRequest(url, "POST", jsonString);
        boolean bool = true;
        if (jsonObject != null) {
            if (0 != jsonObject.getInt("errcode")) {
                bool = false;
            }
        }
        return bool;
    }

    //获取access_token的接口地址（GET）
    private static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    //获取access_token
    public static AccessToken getAccessToken(String appid, String secret) {
        AccessToken accessToken = null;
        String requestUrl = access_token_url.replaceAll("APPID", appid).replaceAll("APPSECRET", secret);
        JSONObject object = HttpRequest(requestUrl, "GET", null);
        if (object != null) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(object.getString("access_token"));
                accessToken.setExpiresIn(object.getInt("expires_in"));
                accessToken.setCreate_time(new Date().getTime() + "");
                accessToken.setType(1);
                System.out.println("获取token成功:" + object.getString("access_token") + "————" + object.getInt("expires_in"));
            } catch (Exception e) {
                accessToken = null;
                // 获取token失败
                String error = String.format("获取token失败 errcode:{} errmsg:{}", object.getInt("errcode"), object.getString("errmsg"));
                System.out.println(error);
            }
        }

        return accessToken;
    }

    /**
     * 获取所有绑定的物流账号
     */


    //获取用户信息的接口地址(snsapi_base方式)
    private static final String userInfoURL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";


    //菜单创建(post)
    public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    //转码
    public static String URLEncoder(String str) {
        String result = str;
        try {
            result = java.net.URLEncoder.encode(result, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    public static String getFileEndWitsh(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }


    /**
     * 数据提交与请求通用方法
     *
     * @param access_token 凭证
     * @param RequestMt    请求方式
     * @param RequestURL   请求地址
     * @param outstr       提交json数据
     */
    public static int PostMessage(String access_token, String RequestMt, String RequestURL, String outstr) {
        int result = 0;
        RequestURL = RequestURL.replace("ACCESS_TOKEN", access_token);
        JSONObject jsonobject = WeixinUtil.HttpRequest(RequestURL, RequestMt, outstr);
        if (null != jsonobject) {
            if (0 != jsonobject.getInt("errcode")) {
                result = jsonobject.getInt("errcode");
                String error = String.format("操作失败 errcode:{} errmsg:{}", jsonobject.getInt("errcode"), jsonobject.getString("errmsg"));
                System.out.println(error);
            }
        }
        return result;
    }


    /**
     * 生成用于获取access_token的Code的Url (授权方式snsapi_base)
     */
    public static String getRequestCodeUrl(String APPID, String redirectUrl) {
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                APPID, redirectUrl, "snsapi_base", "123");

    }

    public static String getRequestCodeUrl3(String APPID, String redirectUrl) {
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                APPID, redirectUrl, "snsapi_base", "1234");

    }

    /**
     * 生成用于获取access_token的Code的Url2(授权方式snsapi_userinfo)
     */
    public static String getRequestCodeUrl2(String APPID, String redirectUrl, String state) {
        System.out.println("生成url:" + redirectUrl);
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                APPID, redirectUrl, "snsapi_userinfo", state);

    }


    /**
     * 发送领取成功通知模板消息
     */
    public static int sendReceiveSuccess_template_message(String openid) {

        AccessToken token = getAccessToken("wxf3f47426a42dadf9", "9805dad9babdcabb824e208f5a946db3");
        //获取参数access_token
        String access_token = token.getToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        LotteryTemplates temp = new LotteryTemplates();
        //
        String Url = "";// 跳转页面
        temp.setUrl(Url);
        temp.setTouser(openid);
        temp.setTopcolor("#000000");
        temp.setTemplate_id("GCSooVpNQpNr6zsfeN6hnFXyc8uB-OI_i8DH0hK56KQ");
        Map<String, TemplateData> m = new HashMap<String, TemplateData>();
        TemplateData first = new TemplateData();
        String effectVal = "未激活";
        String lotterySchedule = "";
   		/* if(message.getLotterySchedule()!="null" && !message.getLotterySchedule().equals("null")){
   			 System.out.println("排期："+message.getLotterySchedule());
   			effectVal="已生效 未开奖";
   			lotterySchedule=" 第"+message.getLotterySchedule()+"期";
   		 }
   		 
   		if(message.getNickname()!=""){
   			first.setValue("由【"+message.getBusinessName()+"】提供的奖券已放入您的口袋啦！");
  		 }else{
  			first.setValue(message.getNickname()+"，由【"+message.getBusinessName()+"】提供的奖券已放入您的口袋啦！");
  		 }
   		 first.setColor("#173177");
   		 m.put("first", first);  
   		 
   		 TemplateData temp2 = new TemplateData();
   		 temp2.setValue(message.getNickname());
   		 temp2.setColor("#173177");
   		 m.put("toName", temp2);  
   		 
   		 TemplateData temp3 = new TemplateData();
  		 temp3.setValue(message.getLotteryName()+lotterySchedule+" \n号码："+WeixinUtil.getLotteryNum(message.getLotteryName(),message.getLotteryNumber())+"\n状态："+effectVal);
  		 temp3.setColor("#173177");
  		 m.put("gift", temp3); 
  		 
  		 
  		 TemplateData temp4 = new TemplateData();
  		 DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  		 temp4.setValue(""+formatter.format(message.getCreateDate()));
  		 temp4.setColor("#173177");
  		 m.put("time", temp4); 
  		 System.out.println("彩票排期："+message.getLotterySchedule());
  		 if(message.getLotterySchedule()!="null" && !message.getLotterySchedule().equals("null")){
  			 TemplateData temp6 = new TemplateData();
  			 temp6.setValue("更多欢乐更多优惠尽在"+message.getBusinessName()+"！\n点此查看赠品详情。 ");
  			 temp6.setColor("#173177");
  			 m.put("remark", temp6);
  		 }else{
  			 TemplateData temp6 = new TemplateData();
  			 temp6.setValue("【"+message.getBusinessName()+"】提醒您：该奖券需激活后生效。"+"\n更多欢乐更多优惠尽在"+message.getBusinessName()+"！ "+"\n点此查看赠品详情。");
  			 temp6.setColor("#173177");
  			 m.put("remark", temp6);
  		 }*/


        String jsonString = JSONObject.fromObject(temp).toString();
        System.out.println(jsonString);

        JSONObject jsonObject = WeixinUtil.HttpRequest(url, "POST", JSONObject.fromObject(temp).toString());
        int result = 0;
        if (jsonObject != null) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
                System.out.println(result);
            }
        }
        return result;
    }

}
